var express = require("express");
var path = require("path");
const bodyParser = require('body-parser')
const mongodb = require('mongodb')
const cookieSession = require('cookie-session');

var app = express();

app.use(bodyParser());
app.use(cookieSession({
    name: 'session',
    keys: ['key1', 'key2']
}))

app.set("view engine", "ejs");

app.set("views", path.resolve(__dirname, "views"));

app.use((req, res, next) => {
    if (req.session.loggedIn) {
        res.local('authenticated', true);
        app.users.findOne({ _id: {$oid: req.session.loggedIn} }, (err, doc) => {
            if (err) return next(err);
            res.local('me', doc);
            next();
        })
    } else {
        res.local('authenticated', false)
        next();
    }
})


app.get("/", function(req, res) {
    res.render("index", { authenticated: false });
});

app.get('/login/:signupEmail', (req, res) => {
    res.render('login', { signupEmail: req.params.signupEmail });
})

app.get('/signup', (req, res) => {
    res.render('signup')
})

app.get('/logout', (req, res) => {
    req.session.loggedIn = null;
    res.redirect('/')
})

app.post('/signup', (req, res, next) => {
    console.log(req.body.user)
    // res.render('/login')
    app.users.insert(req.body.user, (err, doc) => {
        if (err) return next(err);
        res.redirect('/login/' + doc[0].email);
    })
})

app.post('/login', (req, res, next) => {
    const { email, password } = req.body.user
    app.users.findOne({ email, password }, (err, doc) => {
        if (err) return next(err);
        if (!doc) return res.send('<p>User not found. Go back and try again</p>');
        res.session.loggedIn = doc._id.toString();
        res.redirect('/');
    })
})


const server = new mongodb.Server('148.70.78.66', 27017)

new mongodb.Db('user-auth', server).open((err, client) => {
    if (err) throw err;
    console.log('connected mongodb is reday');
    app.users = new mongodb.Collection(client, 'users');

    client.ensureIndex('users', 'email', (err) => {
        if (err) throw err;
        client.ensureIndex('users', 'password', (err) => {
            if (err) throw err;
            console.log('ensureed indexes');

            // 监听
            app.listen(3000, () => {
                console.log('server start http://localhost:3000/')
            });
        })
    })

})
